# coding=utf-8
import pandas as pd
import datetime
import numpy as np


# 画格子，返回格子信息（id，最小经度，最大经度，最小纬度，最大纬度）
def divide_grid(num, max_longitude, min_longitude, max_latitude, min_latitude):

    longitude_unit = (max_longitude - min_longitude) / num
    latitude_unit = (max_latitude - min_latitude) / num
    longitude_edge = [min_longitude + longitude_unit * i for i in range(0, num + 1)]
    latitude_edge = [min_latitude + latitude_unit * i for i in range(0, num + 1)]

    grid_id = [i for i in range(num*num)]
    grid_min_longitude = longitude_edge[:-1] * num
    grid_max_longitude = longitude_edge[1:] * num
    grid_min_latitude = sorted(latitude_edge[:-1] * num)
    grid_max_latitude = sorted(latitude_edge[1:] * num)
    grids = pd.DataFrame([grid_id, grid_min_longitude, grid_max_longitude, grid_min_latitude, grid_max_latitude]).T
    columns = ['grid_id', 'grid_min_longitude', 'grid_max_longitude', 'grid_min_latitude', 'grid_max_latitude']
    grids.columns = columns
    return grids


# 输入经纬度向量，以及分块情况，经纬度起终点，返回对应的grid id
def map_grid(longitudes, latitudes, num, max_longitude, min_longitude, max_latitude, min_latitude):
    longitude_unit = (max_longitude - min_longitude) / num
    latitude_unit = (max_latitude - min_latitude) / num
    grid_id = (longitudes-min_longitude)//longitude_unit + (latitudes-min_latitude)//latitude_unit*num
    return grid_id

